package controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"personal-blog/logic"
	"personal-blog/models"
	"strconv"
)

//  CreateBlog 创建博客
func CreateBlog(c *gin.Context) {
	//获取参数  参数校验
	var blog models.Blog
	if err := c.ShouldBindJSON(&blog); err != nil {
		ResponseErrorWithMsg(c, CodeInvalidParams, err.Error())
		return
	}
	// 获取作者Name，当前请求的UserName
	userName, err := getCurrentUserName(c)
	if err != nil {
		zap.L().Error("GetCurrentUserName() failed", zap.Error(err))
		ResponseError(c, CodeNotLogin)
		return
	}
	blog.Author = userName

	err = logic.CreateBlog(&blog)
	if err != nil {
		zap.L().Error("logic.CreateBlog failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, nil)
}

//UserDetailHandler用户博客列表
func UserDetailHandler(c *gin.Context) {
	//1.获取用户名
	nameStr := c.Param("username") //获取URL参数
	fmt.Println(nameStr)
	//2.根据用户名 获取博客详情
	data, err := logic.GetUserDetail(nameStr)
	if err != nil {
		zap.L().Error("mysql.GetUserDetail() failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, data)
}

// BlogDetailHandler博客详情
func BlogDetailHandler(c *gin.Context) {
	//1.获取博客ID
	idStr := c.Param("blogid") //获取URL参数
	fmt.Println(idStr)
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		ResponseError(c, CodeInvalidParams)
		return
	}
	//2.根据id 获取社区详情
	data, err := logic.GetBlogDetail(id)
	if err != nil {
		zap.L().Error("mysql.GetBlogDetail() failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, data)
}

// BlogAllHandler 查看所有的文章
func BlogAllHandler(c *gin.Context) {
	//获取数据
	data, err := logic.GetBlogList(getPageInfo(c))
	if err != nil {
		zap.L().Error("Logic.GetBlogList() failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	//返回响应
	ResponseSuccess(c, data)
}

// UpdateBlogDetailHandler修改文章
func UpdateBlogDetailHandler(c *gin.Context) {
	//1.获取博客ID
	idStr := c.Param("blogid") //获取URL参数
	fmt.Println(idStr)
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		ResponseError(c, CodeInvalidParams)
		return
	}
	var blog models.Blog
	if err := c.ShouldBindJSON(&blog); err != nil {
		ResponseErrorWithMsg(c, CodeInvalidParams, err.Error())
		return
	}
	//2.根据id 获取博客详情
	err = logic.UpdateBlogDetail(id, &blog)
	if err != nil {
		zap.L().Error("mysql.UpdateBlogDetail() failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, nil)
}

//DeleteBlogDetailHandler删除博客
func DeleteBlogDetailHandler(c *gin.Context) {
	//1.获取博客ID
	idStr := c.Param("blogid") //获取URL参数
	fmt.Println(idStr)
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		ResponseError(c, CodeInvalidParams)
		return
	}
	//2.根据id 获取博客详情
	err = logic.DeleteBlogDetail(id)
	if err != nil {
		zap.L().Error("mysql.DeleteBlogDetail() failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, nil)
}
